<script setup>
import { defineAsyncComponent, inject, onMounted, reactive, ref } from 'vue';

import { cloneDeep } from '@vben/utils';

import { Edit } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

import { requestApi } from '#/api/index.ts';
import useTableHooks from '#/tools/tableHooks';
import { getRulesForEditOption } from '#/utils';

const TableList = defineAsyncComponent(
  () => import('#/component/tableList/index.vue'),
);
const EditAndView = defineAsyncComponent(
  () => import('#/component/detailComp/EditAndView.vue'),
);
const $baseTableHeight = inject('$baseTableHeight');
const loading = ref(false);
const option = reactive({
  tableList: [],
  tableListLoading: false,
  total: 1,
  index: false,
  queryForm: {
    pageNum: 1,
    pageSize: 20,
    delFlag: 0,
  },
  height: $baseTableHeight(44 + 42),
  rowbg: [{ prop: 'status', value: 1, method: '=', class: 'warning-row' }],
  type: '',
  treeKey: '',
  columns: {
    searchContent: [
      {
        type: 'Input',
        value: 'k',
        label: '搜索框',
        placeholder: '模糊检索，支持空格(或)和 +(并)',
      },
      { type: 'Input', value: 'apiNo', label: '配置编号' },
      { type: 'Input', value: 'apiName', label: '配置名称' },
    ],
    tableColumns: [
      { label: 'ID', prop: 'id', width: 80 },
      { label: '配置编号', prop: 'apiNo', sortable: false, width: 350 },
      { label: '配置名称', prop: 'apiName', sortable: false, width: 350 },
      { label: '备注', prop: 'remarks', sortable: false },
    ],
  },
  api: {
    list: {
      url: '/api/Common/GetDataPage?no=COMAPI-ApiConfig',
      method: 'get',
    },
    add: {
      url: '/api/Common/Insert?no=COMAPI-ApiConfig',
      method: 'post',
    },
    edit: {
      url: '/api/Common/Update?no=COMAPI-ApiConfig',
      method: 'post',
    },
    delete: {
      url: '/api/Common/Delete?no=COMAPI-ApiConfig',
      method: 'post',
    },
  },
});
// 添加 & 编辑
const formRef = ref({});
const editDrawer = ref(false);
const rules = ref({});
const editOption = ref({
  title: '',
  columnCount: 2,
  editStatus: false,
  editType: '',
  items: [
    {
      label: 'API配置编号',
      prop: 'apiNo',
      disabled: false,
      display: true,
      inputSet: { type: 'input' },
      rules: {
        required: false,
        trigger: 'blur',
        message: '请输入',
        more: [{ max: 200, message: '最多200字符' }],
      },
    },
    {
      label: 'API配置名称',
      prop: 'apiName',
      disabled: false,
      display: true,
      inputSet: { type: 'input' },
      rules: {
        required: false,
        trigger: 'blur',
        message: '请输入',
        more: [{ max: 200, message: '最多200字符' }],
      },
    },
    // { label: "", display: true, inputSet: { type: 'none' } },
    {
      label: 'API配置',
      prop: 'apiOption',
      display: true,
      inputSet: { type: 'textarea' },
      rules: {
        required: false,
        trigger: 'blur',
        message: '请输入备注',
        more: [],
      },
      span: 2,
    },
    {
      label: '备注',
      prop: 'remarks',
      display: true,
      inputSet: { type: 'textarea' },
      rules: {
        required: false,
        trigger: 'blur',
        message: '请输入备注',
        more: [{ max: 500, message: '最多1500字符' }],
      },
      span: 2,
    },
  ],
  dataModel: {
    id: '',
    remarks: '',
    companyId: '',
    createBy: '',
    createDate: '',
    updateBy: '',
    updateDate: '',
    delFlag: '',
    files: '',
    apiNo: '',
    apiName: '',
    status: '',
    apiOption: '',
  },
  data: {},
});
onMounted(async () => {
  await fetchData(option.queryForm);
});
const getRules = () => {
  if (editOption.value.editStatus) {
    rules.value = getRulesForEditOption(editOption.value);
  } else {
    rules.value = {};
  }
};
const clearEditData = () => {
  // 清空对象数据
  editOption.value.data = cloneDeep(editOption.value.dataModel);
  for (const key in editOption.value.data) {
    let defaultValue = '';
    editOption.value.items.find((item) => {
      if (item.prop === key) {
        defaultValue = item.inputSet?.default ?? '';
      }
    });
    editOption.value.data[key] = defaultValue;
  }
};
const handleDetail = (row) => {
  editDrawer.value = true;
  editOption.value.title = '详情';
  editOption.value.editStatus = false;
  editOption.value.data = cloneDeep(row);
};
const { editRef, fetchData, changeSearch, handleDelete } =
  useTableHooks(option);
const handleAdd = () => {
  editDrawer.value = true;
  editOption.value.title = '添加';
  editOption.value.editStatus = true;
  editOption.value.editType = 'add';
  clearEditData();
};
const handleEdit = (row) => {
  editDrawer.value = true;
  editOption.value.title = '编辑';
  editOption.value.editStatus = true;
  editOption.value.editType = 'edit';
  editOption.value.data = cloneDeep(row);
};
const handleCopy = (row) => {
  editDrawer.value = true;
  editOption.value.title = '复制';
  editOption.value.editStatus = true;
  editOption.value.editType = 'add';
  editOption.value.data = cloneDeep(row);
};
const handleRemoveConfigFlie = async (row = null) => {
  let url = '/api/Common/RemoveApiConfigFlie?configNo=';
  if (row) {
    url = url + row.apiNo;
  }
  const { allCount, data, code } = await requestApi(url, [], 'get');
  console.log(data, code);
  if (code === 2000) {
    ElMessage.success('缓存文件清除成功！');
  } else {
    ElMessage.error('操作失败！');
  }
};
const handleClose = () => {
  editDrawer.value = false;
};
const handleSubmit = () => {
  getRules();
  loading.value = true;
  formRef.value.validate(async (valid) => {
    if (valid) {
      const params = {
        ...editOption.value.data,
      };
      // 数据处理
      editOption.value.items.forEach((item) => {
        if (item.inputSet.type === 'cascade') {
          params[item.prop] = params[item.prop][params[item.prop].length - 1];
        }
      });

      const url =
        editOption.value.editType === 'add'
          ? option.api.add.url
          : option.api.edit.url;
      const method =
        editOption.value.editType === 'add'
          ? option.api.add.method
          : option.api.edit.method;
      const res = await requestApi(url, params, method);
      if (res.code === 2000) {
        ElMessage.success('操作成功');
        await fetchData(option.queryForm);
        close();
      }
      loading.value = false;
      editDrawer.value = false;
    } else {
      loading.value = false;
    }
  });
};
</script>
<template>
  <div class="tableList-container">
    <TableList
      :option="option"
      @change-search="changeSearch"
      @refresh="fetchData"
    >
      <template #searchButton="{ selectRows }">
        <el-button icon="Plus" type="success" @click="handleAdd()">
          添加
        </el-button>
        <el-button icon="delete" plain @click="handleRemoveConfigFlie()">
          清除缓存文件
        </el-button>
      </template>
      <template #tabButton="{ row }">
        <el-button
          bg
          icon="Document"
          plain
          text
          title="查看"
          type="info"
          @click="handleDetail(row)"
        >
          查看
        </el-button>
        <el-dropdown
          class="el-dropdown-link"
          icon="edit"
          plain
          split-button
          type="default"
          @click="handleEdit(row)"
        >
          <el-icon><Edit /></el-icon>&nbsp;&nbsp;编辑
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item icon="delete" @click="handleDelete(row)">
                删除
              </el-dropdown-item>
              <el-dropdown-item icon="CopyDocument" @click="handleCopy(row)">
                复制
              </el-dropdown-item>
              <el-dropdown-item
                icon="CopyDocument"
                @click="handleRemoveConfigFlie(row)"
              >
                清除缓存文件
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </TableList>
    <el-drawer
      v-model="editDrawer"
      :close-on-click-modal="false"
      :modal="false"
      :title="editOption.title"
      class="detail_drawer"
      direction="rtl"
      modal-class="drawerModal"
      size="50%"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="editOption.data"
        :rules="rules"
        label-position="right"
        label-suffix="："
        label-width="0px"
      >
        <EditAndView :option="editOption" />
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button
          v-if="editOption.editStatus"
          :loading="loading"
          type="primary"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </template>
    </el-drawer>
  </div>
</template>
<style scoped lang="scss"></style>
